package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component("securityUserService")
public class SecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //调用userService层方法查询数据库中用户信息
        User user = userService.findByUsername(s);

        //对用户进行判断
        if(user == null){
            //说明数据库中没有此用户，认证失败
            return null;
        }

        //取出user的角色和权限,存入list集合，最后赋值给返回的user对象中
        List<GrantedAuthority> list = new ArrayList<>();

        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //取出的时每一个角色,将角色加入到权限集合中
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //取出此角色的所有权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //取出的是每一个permission权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //此时的list集合中存放的是该用户的所有角色和权限
        System.out.println(s+"===="+user.getPassword());

        return new org.springframework.security.core.userdetails.User(s, user.getPassword(), list);
    }
}
